<?php
/**
 * Created by PhpStorm.
 * Use : 定时扫描服务器磁盘文件
 * User: kan.yang@starcor.cn
 * Date: 18-3-22
 * Time: 下午6:40
 */
set_time_limit(0);
include_once dirname(dirname(dirname(__FILE__)))."/common.php";
\ns_core\m_load::load("ns_core.m_config");
\ns_core\m_load::load("ns_core.m_split_file");
class medium
{
    private $obj_dc = null;

    private $obj_redis_dc = null;

    private $int_limit = 5;

    private $timer_path = '';

    private $child_path = '';

    private $str_file_path = '';

    private $str_split_path = '';

    private $str_date_now = '';

    private $bool_linux_sys= true;

    /**
     * 默认构造函数
     */
    public function __construct()
    {
        $this->obj_dc = m_config::get_dc();
        $this->obj_redis_dc = m_config::get_redis_dc();
        $this->timer_path = m_config::return_child_path(__FILE__);
        //导出文件保存路径
        $this->str_file_path  = dirname(dirname(dirname(dirname(__FILE__)))) . '/data/medium/tree/';
        //切割文件保存路径
        $this->str_split_path  = dirname(dirname(dirname(dirname(__FILE__)))) . '/data/medium/split/';
        //检测新系统环境
        $this->bool_linux_sys = substr(php_uname(), 0, 7) == "Windows" ? false : true;
    }

    /**
     * 定时器入口
     */
    public function init()
    {
        m_config::timer_write_log($this->timer_path,"-----------扫描服务器磁盘文件开始------------",$this->child_path);
        $str_filed = 'd.nns_id,d.nns_server_id,d.nns_disk_path,s.nns_server_path,IF(d.nns_disk_extension IS NULL OR d.nns_disk_extension = \'\',s.nns_server_extension, d.nns_disk_extension) nns_extension';
        $str_sql = "SELECT " . $str_filed . " FROM
                      nns_medium_library_disk d
                      LEFT JOIN nns_medium_library_server s
                        ON s.nns_id = d.nns_server_id
                    WHERE d.nns_state = 0
                      AND s.nns_state = 0";
        $arr_disk_list = nl_query_by_db($str_sql,$this->obj_dc->db());
        if(!is_array($arr_disk_list) || empty($arr_disk_list))
        {
            m_config::timer_write_log($this->timer_path,"查询挂载文件服务器列表数据失败，SQL：" . $str_sql,$this->child_path);
            return false;
        }
        //Redis配置KEY
        $str_cache_key = nl_view_cache::gkey('medium_library_server_disk_list',array('medium_library_server_disk_list',__FILE__));
        $arr_redis_list = nl_queue_redis::get_list($this->obj_redis_dc, $str_cache_key);
        //创建文件夹
        $arr_create_file_ret = $this->_create_save_path($this->str_file_path);
        if($arr_create_file_ret['ret'] != 0)
        {
            return false;
        }
        //创建切割文件夹
        $arr_create_file_ret = $this->_create_save_path($this->str_split_path);
        if($arr_create_file_ret['ret'] != 0)
        {
            return false;
        }
        //遍历磁盘
        $int_init = 0;
        foreach($arr_disk_list as $info)
        {
            if($int_init > $this->int_limit) break;
            if(isset($arr_redis_list) && in_array($info['nns_id'], $arr_redis_list))
            {
                continue;
            }
            //扫描磁盘
            $this->_read_disk_file($info);
            //已扫描的磁盘计入Redis
            nl_queue_redis::push($this->obj_redis_dc, $str_cache_key, $info['nns_id']);
            //睡眠 + 下一次循环
            $int_init ++; usleep(50000);
        }
        //清空Redis数据
        if($int_init == 0)
        {
            nl_queue_redis::delete_key($this->obj_redis_dc, $str_cache_key);
        }
        m_config::timer_write_log($this->timer_path,"-----------扫描服务器磁盘文件结束------------",$this->child_path);

        return true;
    }

    /**
     * 扫描磁盘文件
     */
    private function _read_disk_file($arr_disk_info)
    {
        //磁盘路径
        $str_disk_path = rtrim($arr_disk_info['nns_server_path'],'/') . '/' . trim($arr_disk_info['nns_disk_path'],'/') . '/';
        //导出路径
        $str_txt_path = $this->str_file_path . $arr_disk_info['nns_id'] . '.txt';
        //操作系统
        $str_order = '';
        if ($this->bool_linux_sys)
        {//LINUX下执行

            $str_extension = '-fiN';
//             if(isset($arr_disk_info['nns_extension']) && strlen($arr_disk_info['nns_extension']) > 0)
//             {
//                 $arr_disk_info['nns_extension'] = explode(',', $arr_disk_info['nns_extension']);
//                 $arr_disk_info['nns_extension'] = '*.' . implode('|*.', $arr_disk_info['nns_extension']);
//                 $str_extension .= 'P "' . $arr_disk_info['nns_extension'] . '"';
//             }
            $str_order = 'tree ' . $str_extension  . ' ' . $str_disk_path . ' > ' . $str_txt_path;
            echo $str_order;die;
        }
        else
        {//windows下执行

            $str_order = 'tree ';
        }
        exec($str_order);
        //切割文件
        if(file_exists($str_txt_path) && filesize($str_txt_path) > 0)
        {
            @chmod($str_txt_path,0777);
            //创建切割后保存文件目录
            $this->str_split_path .= $arr_disk_info['nns_id'] . '/';
            if(!is_dir($this->str_split_path))
            {
                @mkdir($this->str_split_path,0777,true);
            }
            //切割大文件
            $obj_split_file = new m_split_file(
                $str_txt_path,'txt',rtrim($this->str_split_path,'/'),__DIR__,1,1000,'medium_','',1
            );
            $arr_split_ret = $obj_split_file->run();
            //切割完成
            if($arr_split_ret['ret'] == 0)
            {
                @chmod($str_txt_path,0777);
            }
        }
    }

    /**
     * 创建CSV保存路径
     */
    private function _create_save_path(&$str_file_path)
    {
        $this->str_date_now = date('Ymd');
        $str_file_path .= $this->str_date_now . '/';
        //验证目录最后是否以“/”结尾
        if(strrchr($str_file_path, '/') != '/')
        {
            $str_file_path .= '/';
        }
        //创建文件目录
        if(!is_dir($str_file_path))
        {
            $bool_dir_ret = mkdir($str_file_path,0777,true);
            if(!$bool_dir_ret)
            {
                m_config::timer_write_log($this->timer_path,'导出片源数据的保存路径创建失败。路径：' . $str_file_path,$this->child_path);
                return $this->_callback_info(1,'导出片源数据的保存路径创建失败。路径：' . $str_file_path);
            }
        }
        return $this->_callback_info(0,'导出片源数据的保存路径创建成功，路径：' . $str_file_path);
    }

    /**
     * 递归遍历文件夹
     */
    private function _get_dir_child_file($str_dir, &$arr_file_path)
    {
        $str_dir = rtrim($str_dir,'/') . '/';
        if(@$obj_handle = opendir($str_dir))
        {
            $str_file_path = '';
            while(($str_file = readdir($obj_handle)) !== false)
            {
                //排除根目录
                if($str_file == ".." || $str_file == ".") continue;

                $str_file_path = $str_dir . $str_file;
                if(is_dir($str_file_path))
                {//文件夹，递归

                    $this->_get_dir_child_file($str_file_path, $arr_file_path);
                } else
                {//文件存入数组

                    $arr_file_path[] = $str_file_path;
                }
            }
            closedir($obj_handle);
        }
        return true;
    }

    /**
     * 输出结果
     * @param int $int_ret
     * @param string $str_reason
     * @return bool
     */
    private function _callback_info($int_ret = 0,$str_reason = '',$arr_data = null)
    {
        return array('ret' => $int_ret, 'reason' => $str_reason,'data' => $arr_data);
    }
}

$obj_medium = new medium();
$obj_medium->init();

